<?php

namespace mpend\modules\app\models;

use Yii;
use common\models\feedback\Feedback;
use common\models\app\AppToken;
use common\helpers\IpHelper;
use common\helpers\ArrayHelper;

/**
 * 反馈意见提交模型
 * 
 * @author emhome<emhome@163.com>
 * @since 2.0
 */
class FeedbackForm extends \common\base\Model {

    /**
     * @var AppToken 接口token
     */
    public $token;

    /**
     * @var integer 应用场景ID
     */
    public $scene_id;

    /**
     * @var string 反馈意见内容
     */
    public $content;

    /**
     * @var string 手机号
     */
    public $mobile;

    /**
     * @inheritdoc
     */
    public function rules() {
        return [
            [['token', 'content', 'mobile'], 'required'],
            [['scene_id'], 'integer'],
            [['content'], 'string', 'max' => 255],
            [['mobile'], 'string', 'max' => 11],
            [['token'], 'validateToken'],
        ];
    }

    /**
     * {@inheritdoc}
     */
    public function attributeLabels() {
        return [
            'scene_id' => '应用场景',
            'content' => '反馈意见内容',
            'mobile' => '手机号',
        ];
    }

    /**
     * 校验购物车中的商品
     * @param string $attribute the attribute currently being validated
     */
    public function validateToken($attribute) {
        if ($this->hasErrors()) {
            return;
        }
        $token = $this->$attribute;
        if (!$token) {
            $this->addError($attribute, '请求TOKEN不能为空');
        } elseif (!($token instanceof AppToken)) {
            $this->addError($attribute, '请求TOKEN非法');
        }
    }

    /**
     * 保存意见内容
     * @return mixed
     */
    public function save() {
        if (!$this->validate()) {
            return $this->dumpError();
        }
        $model = new Feedback();
        $attributes = ArrayHelper::merge($this->attributes, [
            'user_id' => $this->token->user_id,
            'device_id' => $this->token->device_id,
            'ip' => IpHelper::ip(),
        ]);
        $model->setAttributes($attributes);
        if (!$model->save()) {
            return $this->dumpError($model->getErrorMsg(), false);
        }
        return true;
    }

}
